package com.duojuhe.common.utils.page;

import com.duojuhe.common.bean.PageHead;
import com.duojuhe.common.bean.PageReq;
import com.duojuhe.common.exception.base.DuoJuHeException;
import com.duojuhe.common.result.ErrorCodes;
import com.duojuhe.common.result.PageResult;
import com.duojuhe.common.result.ServiceResult;
import com.duojuhe.common.utils.excel.ExcelField;
import com.duojuhe.common.utils.excel.ExportExcelUtil;
import com.duojuhe.common.utils.sqlutils.SqlInjectionUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class PageHelperUtil {

    /**
     * 启动返回结果处理
     *
     * @param dataList 需要处理的数据集合
     */
    public static <T> ServiceResult returnServiceResult(PageReq pageReq, List<T> dataList) {
        try {
            List<ExcelField> excelFieldList = pageReq.getExcelFieldList();
            if (excelFieldList == null || excelFieldList.size() == 0) {
                if (dataList == null) {
                    dataList = new ArrayList<>();
                    return ServiceResult.ok(new PageResult<>(dataList, 0L));
                }
                // 分页处理
                PageInfo<T> pageInfo = new PageInfo<>(dataList);
                return ServiceResult.ok(new PageResult<>(dataList, pageInfo.getTotal()));
            } else {
                if (dataList == null) {
                    dataList = new ArrayList<>();
                }
                ExportExcelUtil.exportExcel(dataList, excelFieldList);
                return null;
            }
        } catch (Exception e) {
            throw new DuoJuHeException(ErrorCodes.FAIL);
        }
    }

    /**
     * 启动返回结果处理
     *
     * @param dataList 需要处理的数据集合
     */
    public static <T> ServiceResult returnServiceResult(List<T> dataList) {
        try{
            // 分页处理
            PageInfo<T> pageInfo = new PageInfo<>(dataList);
            return ServiceResult.ok(new PageResult<>(dataList, pageInfo.getTotal()));
        }catch (Exception e){
            throw new DuoJuHeException(ErrorCodes.FAIL);
        }
    }


    /**
     * 启用单排序
     */
    public static void defaultOrderBy(String defaultOrderBy) {
        if (StringUtils.isEmpty(defaultOrderBy)) {
            return;
        }
        Page page = getPage();
        page.setUnsafeOrderBy(defaultOrderBy);
    }

    /**
     * 启用单分页
     */
    public static void defaultStartPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
    }


    /**
     * 启动排序和分页
     *
     * @param defaultOrderBy 默认无排序字段，设为null或空
     */
    public static void orderByAndStartPage(PageHead pageHead, String defaultOrderBy) {
        // 分页处理
        if (pageHead != null && pageHead.getRows() > 0) {
            Page page = PageHelper.startPage(pageHead.getPage(), pageHead.getRows());
            // 排序
            String orderBy = getOrderBy(pageHead, defaultOrderBy);
            if (StringUtils.isNotBlank(orderBy)) {
                page.setUnsafeOrderBy(orderBy);
            }
        } else {
            defaultOrderBy(defaultOrderBy);
        }
    }


    /**
     * 清除ThreadLocal 缓存
     */
    public static void clearPage() {
        PageHelper.clearPage();
    }


    /**
     * 获取排序
     *
     * @param pageHead
     * @return
     */
    private static String getOrderBy(PageHead pageHead, String defaultOrderBy) {
        //参数传的参数
        String orderBy = pageHead.getOrderBy();
        //判断排序
        if (StringUtils.isNotBlank(orderBy)) {
            //判断sql注入处理
            if (SqlInjectionUtils.check(orderBy)) {
                throw new PageException("order by [" + orderBy + "] 存在 SQL 注入风险");
            }
            return orderBy;
        } else {
            return defaultOrderBy;
        }
    }


    /**
     * 获得一个分页对象
     *
     * @return
     */
    private static Page getPage() {
        Page page = PageHelper.getLocalPage();
        if (page != null) {
            return page;
        }
        page = PageHelper.startPage(0, 0);
        page.setOrderByOnly(true);
        return page;
    }
}
